package org.lds.message.center.common.util;


import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;

public class JsonUtil {
    private static final Logger LOGGER = Logger.getLogger("com.unisound.medical.common.util.JsonUtil");

    private static ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    public static <T> T fromJson(String json, Class<T> tClass) {
        if (StringUtils.isEmpty(json) || Objects.isNull(tClass)) return null;
        try {
            return mapper.readValue(json, tClass);
        } catch (Exception e) {
            LOGGER.info("fromJson error. cause=" + e.getMessage());
            return null;
        }
    }

    public static String toJson(Object o) {
        if (Objects.isNull(o)) return null;
        try {
            return mapper.writeValueAsString(o);
        } catch (Exception e) {
            LOGGER.info("toJson error. cause=" + e.getMessage());
            return null;
        }
    }

    public static <T> List<T> fromJsonList(String json, Class<T> tClass) {
        if (StringUtils.isEmpty(json) || Objects.isNull(tClass)) return null;
        CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
        try {
            return mapper.readValue(json, listType);
        } catch (IOException e) {
            LOGGER.info("fromJsonList error. cause=" + e.getMessage());
            return null;
        }
    }

    public static String toJson(String[] str) {
        if (str == null || str.length == 0) return null;
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for (int i = 0, size = str.length; i < size; i++) {
            builder.append("\"").append(str[i]).append("\"");
            if (i < size - 1) {
                builder.append(",");
            }
        }
        builder.append("]");
        return builder.toString();
    }

}
